#ifndef QTABLEWIDGETSAVE_H
#define QTABLEWIDGETSAVE_H

#include <QTableWidget>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QFileDialog>

class QTableWidgetSave : public QTableWidget
{
    Q_OBJECT
public:
    explicit QTableWidgetSave(int row = 0, int column = 0,QWidget *parent = nullptr) : QTableWidget(row, column ,parent) {}
    
    // 导出表格为CSV文件
    bool exportToCsv(const QString &fileName, const QString &separator = ",", const QString &encoding = "UTF-8") {
        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QMessageBox::critical(this, "导出失败", "无法打开文件: " + fileName);
            return false;
        }
        
        QTextStream out(&file);
        out.setCodec(encoding.toUtf8());
        
        // 导出表头
//        QStringList headers;
//        for (int col = 0; col < columnCount(); ++col) {
//            headers.append(escapeCsvField(horizontalHeaderItem(col)->text()));
//        }
//        out << headers.join(separator) << "\n";
        
        // 导出数据
        for (int row = 0; row < rowCount(); ++row) {
            QStringList rowData;
            for (int col = 0; col < columnCount(); ++col) {
                QTableWidgetItem *item = this->item(row, col);
                QString text = item ? item->text() : "";
                rowData.append(escapeCsvField(text));
            }
            out << rowData.join(separator) << "\n";
        }
        
        file.close();
        return true;
    }
    
    // 从CSV文件导入数据
    bool importFromCsv(const QString &fileName, const QString &separator = ",", const QString &encoding = "UTF-8") {
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QMessageBox::critical(this, "导入失败", "无法打开文件: " + fileName);
            return false;
        }
        
        // 清空现有数据但保留行列数
        clearContents();
        
        QTextStream in(&file);
        in.setCodec(encoding.toUtf8());
        
        // 读取表头
//        QString headerLine = in.readLine();
//        QStringList headers = parseCsvLine(headerLine, separator);
//        setColumnCount(headers.size());
//        setHorizontalHeaderLabels(headers);
        
        // 读取数据行
        int row = 0;
        while (!in.atEnd()) {
            QString line = in.readLine();
            if (line.trimmed().isEmpty()) continue; // 跳过空行
            
            QStringList fields = parseCsvLine(line, separator);
            
            // 确保列数匹配
            if (fields.size() < columnCount()) {
                fields.append(QStringList());
                fields.last().fill(' ', columnCount() - fields.size());
            }
            
            // 添加行
            if (row >= rowCount()) {
                insertRow(row);
            }
            
            for (int col = 0; col < columnCount() && col < fields.size(); ++col) {
                setItem(row, col, new QTableWidgetItem(fields[col]));
            }
            ++row;
        }
        
        // 调整列宽以适应内容
        resizeColumnsToContents();
        
        file.close();
        return true;
    }
    
    // 打开文件对话框导出CSV
    void exportCsvDialog() {
        QString fileName = QFileDialog::getSaveFileName(
            this, "导出CSV文件", "", "CSV Files (*.csv);;All Files (*)");
        
        if (!fileName.isEmpty()) {
            if (!fileName.endsWith(".csv", Qt::CaseInsensitive)) {
                fileName += ".csv";
            }
            exportToCsv(fileName);
        }
    }
    
    // 打开文件对话框导入CSV
    void importCsvDialog() {
        QString fileName = QFileDialog::getOpenFileName(
            this, "导入CSV文件", "", "CSV Files (*.csv);;All Files (*)");
        
        if (!fileName.isEmpty()) {
            importFromCsv(fileName);
        }
    }

private:
    // 转义CSV字段，处理引号和分隔符
    QString escapeCsvField(const QString &text) const {
        if (text.isEmpty()) return "''";
        
        // 如果字段包含引号、分隔符或换行符，用引号括起来并转义引号
        if (text.contains('"') || text.contains(',') || text.contains('\n')) {
            return "\"" + text + "\""; //直接外层增加""号区分
        }
        
        return text;
    }
    
    // 解析CSV行，处理引号和转义
    QStringList parseCsvLine(const QString &line, const QString &separator) const {
        QStringList fields;
        QString currentField;
        bool inQuotes = false;
        
        for (int i = 0; i < line.length(); ++i) {
            QChar c = line[i];
            
            if (c == '"') {
                // 处理引号
                if (i + 1 < line.length() && line[i + 1] == '"') {
                    // 双引号表示转义的引号
                    currentField.append('"');
                    ++i;
                } else {
                    // 单引号表示引号开始或结束
                    inQuotes = !inQuotes;
                }
            } else if (c == separator && !inQuotes) {
                // 分隔符，且不在引号内
                fields.append(currentField);
                currentField.clear();
            } else {
                // 普通字符
                currentField.append(c);
            }
        }
        
        // 添加最后一个字段
        fields.append(currentField);
        return fields;
    }
};


#endif
